<template>
  <div class="cityLayerBox">
    <div class="checkContent layerAllCheck">
      <el-checkbox
        :indeterminate="layerGroupIndeterminate"
        :value="layerGroupLength != 0 && layerGroupLength == layerList.length"
        @change="layerAllChange"
      >
      </el-checkbox>
      <div class="checkText">全选</div>
    </div>
    <div class="contentList">
      <div
        v-for="layer in layerList"
        :key="layer.layerId"
        class="checkContent layerCheck"
      >
        <el-checkbox
          v-model="layer.layerCheck"
          :indeterminate="layerIndeterminate(layer)"
          @change="layerCheckChange(layer)"
        ></el-checkbox>
        <div
          class="checkText"
          :class="{ selectText: layerSelect.layerId == layer.layerId }"
          @click="openLayerFolder(layer)"
        >
          <div class="checkBall" :style="layerCheckBall(layer)"></div>
          {{ layer.layerName }}
        </div>
      </div>
    </div>
    <div class="folderBox" v-if="!!layerSelect.layerId">
      <div class="folderData" v-if="layerSelect.layerFolderList.length > 0">
        <div class="checkContent layerAllCheck">
          <el-checkbox
            :indeterminate="layerIndeterminate(layerSelect)"
            :value="layerSelect.layerCheck"
            @change="folderAllChange"
          >
          </el-checkbox>
          <div class="folderCheckContent">
            <div class="checkSearch" v-if="folderSearchVisible">
              <el-input
                v-model="folderSearchValue"
                size="mini"
                @change="searchFolder"
                @blur="searchBlur"
              ></el-input>
            </div>
            <div class="checkText" v-else>全选</div>
            <div class="searchButtonIcon" @click="folderSearchChange">
              <i class="el-icon-search" />
            </div>
          </div>
        </div>
        <div class="contentFolderList">
          <template v-for="folder in layerSelect.layerFolderList">
            <div
              v-show="folder.searchVisible"
              :key="folder.folder_id"
              class="checkContent layerCheck"
            >
              <el-checkbox
                v-model="folder.folderCheck"
                @change="folderCheckChange(folder)"
              >
              </el-checkbox>
              <div class="checkText checkLandText">
                <svg-icon
                  v-if="folder.lmcategory_id == 30"
                  :icon-class="folder.block_shape"
                  :style="svgColor(folder)"
                ></svg-icon>
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="folder.folder_name"
                  placement="bottom"
                  :disabled="folder.folder_name.length < 7"
                  popper-class="layerPopper"
                  :open-delay="300"
                >
                  <div class="checkLandText">
                    {{ folder.folder_name }}
                  </div>
                </el-tooltip>
              </div>
            </div>
          </template>
        </div>
      </div>
      <div class="folderNoneData" v-else>
        <svg-icon icon-class="land_city_noneData"></svg-icon>
        暂无数据
      </div>
    </div>
  </div>
</template>

<script>
import { getLandmarkList, getFolderConfig } from "@/api/bottomComponents";

var layerDataList = [
  {
    layerId: 15,
    layerFolderList: [],
  },
  {
    layerId: 30,
    layerFolderList: [],
  },
  {
    layerId: 7,
    layerFolderList: [],
  },
  {
    layerId: 11,
    layerFolderList: [],
  },
];

var textLayer = null;
var textDataList = [];
var textLabelList = [];

export default {
  name: "cityLayerTool",
  props: {
    layerLists: {
      default() {
        return [];
      },
    },
  },
  components: {},
  data() {
    return {
      layerAllCheck: false,
      layerList: [
        {
          layerName: "管辖区",
          layerId: 15,
          layerCheck: false,
          layerIndeterminate: false,
          layerColorOpacity: "#2D8CF050",
          layerColor: "#2D8CF0",
          layerOpacity: "0.15",
          layerFolderList: [],
        },
        {
          layerName: "兴趣区",
          layerId: 30,
          layerCheck: false,
          layerIndeterminate: false,
          layerColorOpacity: "#00BE0050",
          layerColor: "#00BE00",
          layerOpacity: "0.15",
          layerFolderList: [],
        },
        {
          layerName: "禁飞区",
          layerId: 7,
          layerCheck: false,
          layerIndeterminate: false,
          layerColorOpacity: "#D1030C50",
          layerColor: "#D1030C",
          layerOpacity: "0.15",
          layerFolderList: [],
        },
        {
          layerName: "制高点",
          layerId: 11,
          layerCheck: false,
          layerIndeterminate: false,
          layerColorOpacit5y: "#FFCC0250",
          layerColor: "#FFCC02",
          layerOpacity: "0.15",
          layerFolderList: [],
        },
      ],
      layerSelect: {},

      folderAllCheck: false,
      folderAllIndeterminate: false,
      folderSearchVisible: false,
      folderSearchValue: "",
    };
  },
  computed: {
    // 图层选中数量
    layerGroupLength() {
      let list = [];
      this.layerList.forEach((layer) => {
        if (layer.layerCheck) {
          list.push(layer.layerId);
        }
      });
      return list.length;
    },
    // 全部图层-
    layerGroupIndeterminate() {
      return (
        (this.layerGroupLength > 0 || this.layerGroupIndeterminateLength > 0) &&
        this.layerGroupLength < this.layerList.length
      );
    },
    // 全部图层- 数量
    layerGroupIndeterminateLength() {
      let list = [];
      this.layerList.forEach((layer) => {
        if (layer.layerIndeterminate) {
          list.push(layer.layerId);
        }
      });
      return list.length;
    },

    folderGroupLength() {
      let list = [];
      this.layerSelect?.layerFolderList.forEach((folder) => {
        if (folder.folderCheck) {
          list.push(folder.folder_id);
        }
      });
      return list.length;
    },
  },
  mounted() {
    this.initData();
    // this.textLabelShow();
  },
  methods: {
    async initData() {
      // 文字图层
      textLayer = viewer.scene.primitives.add(
        new Cesium.LabelCollection({
          scene: viewer.scene,
        })
      );

      let getFolderConfigParams = {
        platform: 1,
      };

      let landSeeMin = 0;
      let landSeeMax = 50000.0;

      let folderRes = await getFolderConfig(getFolderConfigParams);
      if (folderRes.error_code == 0) {
        let data = folderRes.data || [];
        for (let folder of data) {
          let findLayer = this.layerList.find((layer) => {
            return layer.layerId == folder.lmcategory_id;
          });
          let folderLayer = CesiumUtil.CreateLayer(
            "文件夹" + folder.folder_name + "-" + folder.folder_id
          );
          folderLayer.show = false;
          let landList = [];
          let landRes = await getLandmarkList({
            folder_id: folder.folder_id,
            lmcategory_id: folder.lmcategory_id,
            // dept_id: 1,
          });
          if (landRes.error_code == 0) {
            landList = landRes.data || [];
          }
          if (landList.length == 0) {
            continue;
          }

          if (folder.lmcategory_id == 30) {
            textDataList = [...textDataList, ...landList];
          }
          // 绘制地块
          landList.forEach((land) => {
            let area = JSON.parse(land.landmark_area);
            let areaType = area.type;
            let centerPoint = JSON.parse(land.landmark_center);

            if (folder.lmcategory_id == 30) {
              // 兴趣区
              let landFillColor = folder.block_fill;
              let landLine = folder.block_line_segment;
              let landLineColor = folder.block_line_segment_colour;

              let landPosition = land?.attribute_info?.info.find((position) => {
                return position.position == 1;
              });
              if (!!landPosition) {
                let flagFillColor = false;
                let flagLine = false;
                let flagLineColor = false;
                let findFillColor = null;
                let findLine = null;
                let findLineColor = null;
                landPosition.position_value.forEach((value) => {
                  switch (value.attribute_id) {
                    case 14:
                      flagFillColor = true;
                      findFillColor = value.attribute_value;
                      break;
                    case 17:
                      flagLine = true;
                      findLine = value.attribute_value;
                      break;
                    case 19:
                      flagLineColor = true;
                      findLineColor = value.attribute_value;
                      break;
                    default:
                      break;
                  }
                });

                if (flagFillColor && flagLine && flagLineColor) {
                  landFillColor = findFillColor?.value || "";
                  landLine = findLine?.value || "";
                  landLineColor = findLineColor?.value || "";
                }
              }
              if (areaType == "Polygon") {
                let PolygonArr = [];
                area.coordinates.forEach((polygon) => {
                  PolygonArr = polygon.reduce(function (a, b) {
                    return a.concat([b[0], b[1], b[2] || 200]);
                  }, []);
                });

                let entities = {
                  id: land.landmark_id,
                  name: land.landmark_name,
                  type:
                    folder.folder_name + "-" + folder.folder_id + "-Polygon",
                };
                if (landFillColor) {
                  entities.polygon = {
                    hierarchy:
                      Cesium.Cartesian3.fromDegreesArrayHeights(PolygonArr),
                    material: new Cesium.Color.fromCssColorString(
                      landFillColor
                    ).withAlpha(0.5),
                    distanceDisplayCondition:
                      new Cesium.DistanceDisplayCondition(
                        landSeeMin,
                        landSeeMax
                      ),
                  };
                }
                if (!!landLine) {
                  //  判断是否为虚线
                  let lineMaterial = null;
                  if (landLine == "solid") {
                    lineMaterial = new Cesium.Color.fromCssColorString(
                      landLineColor
                    );
                  } else if (landLine == "dotted") {
                    lineMaterial = new Cesium.PolylineDashMaterialProperty({
                      color: new Cesium.Color.fromCssColorString(landLineColor),
                      // gapColor:Cesium.Color.WHITE,
                      gapColor: Cesium.Color.fromCssColorString(
                        "rgba(255,255,255,0)"
                      ),
                      // gapColor:obj.gep_color?obj.gep_color: ,
                      dashLength: 20,
                    });
                  } else {
                    this.$message.info("其他线");
                  }
                  entities.polyline = {
                    positions:
                      Cesium.Cartesian3.fromDegreesArrayHeights(PolygonArr),
                    width: 2,
                    material: lineMaterial,
                    clampToGround: true,
                    distanceDisplayCondition:
                      new Cesium.DistanceDisplayCondition(
                        landSeeMin,
                        landSeeMax
                      ),
                  };
                }

                folderLayer.entities.add(entities);

                let textPosition = Cesium.Cartesian3.fromDegrees(
                  centerPoint.coordinates[0],
                  centerPoint.coordinates[1]
                );
                // svg
                let svgData = {
                  id: land.landmark_id + "-svg",
                  name: land.landmark_name + "-svg",
                  type: folder.folder_name + "-" + folder.folder_id + "-svg",

                  // 设置实体位置
                  position: textPosition,
                  billboard: {
                    image: require(`./image/${folder.block_shape}.png`),
                    width: 40,
                    height: 40,
                    // scale: 0.1,
                    scaleByDistance: new Cesium.NearFarScalar(
                      100,
                      1.0,
                      5000,
                      0.5
                    ),
                    disableDepthTestDistance: Number.POSITIVE_INFINITY,
                    distanceDisplayCondition:
                      new Cesium.DistanceDisplayCondition(
                        landSeeMax,
                        300000000.0
                      ),
                    color: new Cesium.Color.fromCssColorString(
                      folder.block_colour
                    ),
                  },
                };
                folderLayer.entities.add(svgData);
              } else {
              }
            } else if (folder.lmcategory_id == 11) {
              // 制高点
              if (areaType == "Polygon") {
                let landHeight = 0;
                let PolygonArr = [];
                area.coordinates.forEach((polygon) => {
                  PolygonArr = polygon.reduce(function (a, b) {
                    if (b[2] > landHeight) {
                      landHeight = b[2];
                    }
                    return a.concat([b[0], b[1], b[2]]);
                  }, []);
                });
                let entities = {
                  id: land.landmark_id,
                  name: land.landmark_name,
                  type:
                    folder.folder_name + "-" + folder.folder_id + "-Polygon",
                };
                entities.polygon = {
                  hierarchy:
                    Cesium.Cartesian3.fromDegreesArrayHeights(PolygonArr),
                  material: new Cesium.Color.fromCssColorString(
                    findLayer.layerColor
                  ).withAlpha(0.5),
                  extrudedHeight: landHeight,
                  distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                    landSeeMin,
                    landSeeMax
                  ),
                };
                folderLayer.entities.add(entities);
              } else if (areaType == "Point") {
                let point = {
                  id: land.landmark_id,
                  name: land.landmark_name,
                  type: folder.folder_name + "-" + folder.folder_id + "-Point",

                  position: Cesium.Cartesian3.fromDegrees(
                    area.coordinates[0],
                    area.coordinates[1],
                    area.coordinates[2]
                  ),
                  ellipse: {
                    extrudedHeight: area.coordinates[2],
                    semiMinorAxis: 10,
                    semiMajorAxis: 10,
                    material: new Cesium.Color.fromCssColorString(
                      findLayer.layerColor
                    ).withAlpha(0.5),
                    outline: true,
                    outlineWidth: 4,
                    outlineColor: Cesium.Color.fromCssColorString(
                      findLayer.layerColor
                    ),
                    distanceDisplayCondition:
                      new Cesium.DistanceDisplayCondition(
                        landSeeMin,
                        landSeeMax
                      ),
                  },
                };
                folderLayer.entities.add(point);
              } else if (areaType == "LineString") {
                let lineArr = [];
                lineArr = area.coordinates.reduce(function (a, b) {
                  return a.concat([b[0], b[1], b[2]]);
                }, []);

                let entities = {
                  id: land.landmark_id,
                  name: land.landmark_name,
                  type:
                    folder.folder_name + "-" + folder.folder_id + "-LineString",
                };

                entities.polyline = {
                  positions: Cesium.Cartesian3.fromDegreesArrayHeights(lineArr),
                  width: 2,
                  material: new Cesium.Color.fromCssColorString(
                    findLayer.layerColor
                  ),
                  distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                    landSeeMin,
                    landSeeMax
                  ),
                };

                folderLayer.entities.add(entities);
              } else {
              }
            } else {
              // 其他区块
              if (areaType == "Polygon") {
                let PolygonArr = [];
                area.coordinates.forEach((polygon) => {
                  PolygonArr = polygon.reduce(function (a, b) {
                    return a.concat([b[0], b[1], b[2] || 200]);
                  }, []);
                });

                let entities = {
                  id: land.landmark_id,
                  name: land.landmark_name,
                  type:
                    folder.folder_name + "-" + folder.folder_id + "-Polygon",
                };
                entities.polygon = {
                  hierarchy:
                    Cesium.Cartesian3.fromDegreesArrayHeights(PolygonArr),
                  material: new Cesium.Color.fromCssColorString(
                    findLayer.layerColor
                  ).withAlpha(0.5),
                  distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                    landSeeMin,
                    landSeeMax
                  ),
                };

                entities.polyline = {
                  positions:
                    Cesium.Cartesian3.fromDegreesArrayHeights(PolygonArr),
                  width: 2,
                  material: new Cesium.Color.fromCssColorString(
                    findLayer.layerColor
                  ),
                  clampToGround: true,
                  distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                    landSeeMin,
                    landSeeMax
                  ),
                };

                folderLayer.entities.add(entities);
              } else {
              }
            }
          });
          folder.landList = landList;
          if (!!findLayer) {
            let findDataLayer = layerDataList.find((layer) => {
              return layer.layerId == findLayer.layerId;
            });
            findDataLayer.layerFolderList.push({
              folderId: folder.folder_id,
              folderLayer: folderLayer,
            });
            findLayer.layerFolderList.push({
              ...folder,
              folderCheck: false,
            });
          } else {
            this.$message.warning("文件夹未找到对应图层");
          }
        }

        this.textLabelChange();
      } else {
        this.$message.warning(folderRes.msg);
      }
    },

    // 文字图层变化
    textLabelChange() {
      let landPointList = [];
      textDataList.forEach((land) => {
        landPointList.push({
          geometry: JSON.parse(land.landmark_center),
          properties: { data: land },
          type: "Feature",
        });
      });
      var collection = turf.featureCollection(landPointList);
      var maxDistance = 0.5;
      var clustered = turf.clustersDbscan(collection, maxDistance);
      clustered.features.forEach((feature) => {
        if (feature.properties.dbscan == "noise") {
          let land = feature.properties.data;
          let landArea = JSON.parse(land.landmark_area);
          if (landArea.type != "Polygon") {
            return;
          }
          let centerPoint = JSON.parse(land.landmark_center);
          let textPosition = Cesium.Cartesian3.fromDegrees(
            centerPoint.coordinates[0],
            centerPoint.coordinates[1]
          );
          let labelOption = {
            id: land.folder_id + "--" + land.landmark_id + "-text",
            text: land.landmark_name,
            seeMin: 0,
            seeMax: 50000,
          };
          let textLabel = CesiumUtil.drawText(
            textPosition,
            textLayer,
            labelOption
          );
          textLabelList.push(textLabel);
        }
      });
      turf.clusterEach(clustered, "cluster", function (cluster, clusterValue) {
        let dataList = [];

        for (let feature of cluster.features) {
          dataList.push(feature.properties.data);
        }

        dataList.sort((a, b) => {
          return b.landmark_product - a.landmark_product;
        });
        let dataIndex = 0;

        for (let land of dataList) {
          dataIndex++;
          let landSeeMin = 0;
          let landSeeMax = 50000;

          if (dataIndex > 1) {
            landSeeMax = 4000;
          }
          let landArea = JSON.parse(land.landmark_area);
          if (landArea.type != "Polygon") {
            return;
          }
          let centerPoint = JSON.parse(land.landmark_center);
          let textPosition = Cesium.Cartesian3.fromDegrees(
            centerPoint.coordinates[0],
            centerPoint.coordinates[1]
          );
          let labelOption = {
            id: land.folder_id + "--" + land.landmark_id + "-text",
            text: land.landmark_name,
            seeMin: landSeeMin,
            seeMax: landSeeMax,
          };
          let textLabel = CesiumUtil.drawText(
            textPosition,
            textLayer,
            labelOption
          );
          textLabelList.push(textLabel);
        }
      });
    },

    // 图层全选
    layerAllChange() {
      let flag = true;
      if (this.layerGroupLength == this.layerList.length) {
        flag = true;
      } else {
        flag = false;
      }
      this.layerList.forEach((layer) => {
        layer.layerCheck = !flag;
        layer.layerFolderList.forEach((folder) => {
          this.folderShowChange(folder, !flag);
        });
      });
    },
    // 文件夹全选
    folderAllChange() {
      let flag = true;
      if (this.folderGroupLength == this.layerSelect.layerFolderList.length) {
        flag = true;
      } else {
        flag = false;
      }
      this.layerSelect.layerCheck = !flag;
      this.layerSelect.layerFolderList.forEach((folder) => {
        this.folderShowChange(folder, !flag);
      });
    },
    // 图层球css
    layerCheckBall(layer) {
      return `backgroundColor:${layer.layerColorOpacity};border: 1px solid ${layer.layerColor}`;
    },

    // 打开图层文件夹
    openLayerFolder(layer) {
      if (this.layerSelect.layerId == layer.layerId) {
        this.layerSelect = {};
      } else {
        this.layerSelect = layer;
        this.layerSelect.layerFolderList.forEach((folder) => {
          folder.searchVisible = true;
        });
      }
    },

    // 图层多选
    layerCheckChange(layer) {
      layer.layerFolderList.forEach((folder) => {
        this.folderShowChange(folder, layer.layerCheck);
      });
    },
    // 图层-
    layerIndeterminate(layer) {
      let index = 0;
      layer.layerFolderList.forEach((folder) => {
        if (folder.folderCheck) {
          index++;
        }
      });
      let flag = index > 0 && index < layer.layerFolderList.length;
      return flag;
    },

    // 文件夹多选
    folderCheckChange(folder) {
      this.layerSelect.layerCheck =
        this.folderGroupLength == this.layerSelect.layerFolderList.length;

      this.folderShowChange(folder, folder.folderCheck);
    },

    // 文件夹变动
    folderShowChange(folder, flag) {
      folder.folderCheck = flag;
      console.log("layerDataList", layerDataList);
      let findDataLayer = layerDataList.find((layer) => {
        return layer.layerId == folder.lmcategory_id;
      });
      let dataFolder = findDataLayer.layerFolderList.find((aFolder) => {
        return folder.folder_id == aFolder.folderId;
      });
      console.log("dataFolder", dataFolder);
      dataFolder.folderLayer.show = flag;
      textLabelList.forEach((label) => {
        if (label.id.split("--")[0] == folder.folder_id) {
          label.show = flag;
        }
      });
    },

    svgColor(folder) {
      return "color:" + folder.block_colour;
    },

    folderSearchChange() {
      this.folderSearchVisible = !this.folderSearchVisible;
      if (!this.folderSearchVisible) {
        this.folderSearchValue = "";
        this.searchFolder();
      }
    },
    // 搜索文件夹
    searchFolder() {
      let val = this.folderSearchValue;
      this.layerSelect.layerFolderList = this.layerSelect.layerFolderList.map(
        (folder) => {
          if (!val.trim()) {
            folder.searchVisible = true;
          } else {
            folder.searchVisible = folder.folder_name.includes(val.trim());
          }
          return folder;
        }
      );
    },
    // 搜索失焦
    searchBlur() {
      if (!this.folderSearchValue.trim()) {
        this.folderSearchVisible = false;
      }
      this.searchFolder();
    },
  },
  watch: {},
  beforeDestroy() {
    layerDataList.forEach((layer) => {
      layer?.layerFolderList.forEach((folder) => {
        viewer.dataSources.remove(folder.folderLayer);
      });
    });

    if (!!textLayer) {
      viewer.scene.primitives.remove(textLayer);
    }
  },
};
</script>

<style lang="scss" scoped>
$ballRadius: 12px;
.cityLayerBox {
  position: relative;
  background-color: rgba(85, 170, 255, 0.5);
  color: #fff;
  width: 110px;
  padding: 5px;
  padding-right: 0;
  .contentList {
    display: flex;
    flex-direction: column;
    overflow: auto;
    max-height: 120px;
  }
  .checkContent {
    display: flex;
    &.layerAllCheck {
      margin-bottom: 5px;
      .checkText {
        cursor: default;
      }
    }
    &.layerCheck {
      margin-left: 10px;
      margin-bottom: 5px;
    }
    .checkText {
      flex: 1;
      display: flex;
      margin-left: 5px;
      align-items: center;
      padding-left: 2px;
      padding-right: 5px;
      cursor: pointer;
      .svg-icon {
        margin-right: 5px;
      }
      &.selectText {
        background-color: rgba(85, 170, 255, 0.51);
      }
      .checkBall {
        margin-right: 3px;
        height: $ballRadius;
        width: $ballRadius;
        border-radius: $ballRadius;
      }
      .checkLandText {
        cursor: default;
        width: 90px;
        /* 强制不换行 */
        white-space: nowrap;
        /* 文本溢出隐藏 */
        overflow: hidden;
        /* 省略号 */
        text-overflow: ellipsis;
      }
    }
  }
  .folderBox {
    padding: 5px;
    position: absolute;
    top: 0;
    left: 112px;
    width: 150px;
    background-color: rgba(85, 170, 255, 0.5);
    color: #fff;
    overflow: auto;
    .folderData {
      height: 200px;
      .contentFolderList {
        display: flex;
        flex-direction: column;
        overflow: auto;
        height: 180px;
      }
    }
    .folderNoneData {
      height: 200px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      .svg-icon {
        width: 50px;
        height: 50px;
        margin-bottom: 5px;
      }
    }

    .checkContent {
      .folderCheckContent {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        .checkSearch {
          flex: 1;
          padding-left: 5px;
          .el-input ::v-deep {
            .el-input__inner {
              height: 19px;
              border-radius: 0px;
              padding: 0 2px;
            }
          }
        }
        .searchButtonIcon {
          color: #ffffff;
          background: #14375d;
          border: 1px solid #1989be;
          width: 20px;
          height: 20px;
          line-height: 20px;
          text-align: center;
          cursor: pointer;
          border-right: none;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.el-tooltip__popper.is-dark {
  &.layerPopper {
    background-color: #fff !important;
    color: #000;
    margin-top: 0;
  }
}
</style>